import axios from "axios";
import errorHandle from "./errorHandle";

class HttpRequest {
  static _instance;
  static _insideConfig = {
    baseURL: "http://localhost:50922/",
    headers: {
      "Content-Type": "application/json;charset=utf-8"
    },
    timeout: 10000
  };

  static _getInstance() {
    // 创建单例
    if (!this._instance) {
      const instance = axios.create(this._insideConfig);
      this._instance = instance;
      this.interceptors(instance);
      return instance;
    } else {
      return this._instance;
    }
  }

  static interceptors(instance) {
    instance.interceptors.request.use(
      conf => {
        // console.log("conf", conf);
        return conf;
      },
      err => {
        errorHandle(err);
        return Promise.reject(err);
      }
    );

    instance.interceptors.response.use(
      res => {
        // console.log("res is", res);
        if (res.status === 200) {
          return Promise.resolve(res.data);
        } else {
          return Promise.reject(res);
        }
      },
      err => {
        errorHandle(err);
        return Promise.reject(err);
      }
    );
  }

  static request(options) {
    const instance = this._getInstance();
    return instance(options);
  }

  static get(url, config) {
    const options = Object.assign(
      {
        method: "get",
        url
      },
      config
    );
    return this._getInstance()(options);
  }

  static post(url, data) {
    return this._getInstance()({
      method: "post",
      url,
      data,
    });
  }
}

export default HttpRequest;
